<template>
  <div class="fly-panel fly-panel-user" pad20>
    <div class="layui-tab layui-tab-brief" lay-filter="user" id="LAY_msg" style="margin-top: 15px;">
      <button class="layui-btn layui-btn-danger" id="LAY_delallmsg" @click="readMsg('all')">清空全部消息</button>
      <div id="LAY_minemsg" style="margin-top: 10px;">
        <!--<div class="fly-none">您暂时没有最新消息</div>-->
        <ul class="mine-msg">
          <li data-id="123" v-for="(item,index) in list" :key="'msg' + index">
            <blockquote class="layui-elem-quote">
              <router-link :to="{name: 'home',params: {uid:item.cuid._id}}">
                <cite>{{item.cuid.name}}</cite>
              </router-link>回答了您的求解
              <router-link :to="{name:'detail',params: {tid: item.tid._id}}">
                <cite>{{item.tid.title}}</cite>
              </router-link>
            </blockquote>
            <p>
              <span>{{item.created | formatDate}}</span>
              <a
                @click="readMsg(item)"
                href="javascript:;"
                class="layui-btn layui-btn-small layui-btn-danger fly-delete"
              >删除</a>
            </p>
          </li>
          <!-- <li data-id="123">
            <blockquote class="layui-elem-quote">系统消息：欢迎使用 layui</blockquote>
            <p>
              <span>1小时前</span>
              <a
                href="javascript:;"
                class="layui-btn layui-btn-small layui-btn-danger fly-delete"
              >删除</a>
            </p>
          </li> -->
        </ul>
      </div>
    </div>
    <Pagination v-show="list.length > 0 && total > 0" @changeCurrent="changeCurrent" :total="total" :size="limit" :current="current" :showEnd="false" :showType="'icon'"></Pagination>
  </div>
</template>

<script>
import { getUserMsg, readUserMsg } from '@/api/user'
// import WebSocket from 'ws'
import Pagination from '@/components/modules/pagination/pagination'
export default {
  name: 'user-msg',
  components: {
    Pagination
  },
  data () {
    return {
      list: [],
      current: 0,
      limit: 10,
      total: 100,
      ws: {}
    }
  },
  mounted () {
    // this.init()
    this.getMsg()
  },

  methods: {
    async readMsg (item) {
      let res = {}
      let readAll = false
      if (item === 'all') {
        if (this.list.length === 0) {
          this.$pop('shake', '没有未读消息可以清除')
          return
        }
        readAll = true
        res = await readUserMsg()
      } else {
        res = await readUserMsg({ cid: item._id })
      }
      let num = this.$store.state.num
      if (res.code === 200) {
        if (readAll) {
          this.list = []
          num = 0
        } else {
          this.list.splice(this.list.indexOf(item), 1)
          num--
        }
        this.$store.commit('setNum', num)
      }
    },
    init () {
      this.ws = new WebSocket('ws://127.0.0.1:3001')
      this.ws.onopen = this.onOpen
      this.ws.onmessage = this.onMessage
      this.ws.onclose = this.onClose
      this.ws.onerror = this.onError
    },
    onOpen () {
      this.ws.send(JSON.stringify({
        event: 'auth',
        message: `Bearer ${this.$store.state.token}`
      }))
    },
    onMessage (event) {
      const obj = JSON.parse(event.data)
      switch (obj.event) {
        case 'noauth':
          this.$pop('shake', '鉴权失败')
          break
        case 'heartbeat':
          this.send(JSON.stringify({
            event: 'heartbeat',
            message: 'pong'
          }))
          break
        default:
          break
      }
    },
    onClose () {
      // console.log('连接关闭' + this.ws.readyState)
      this.ws.close()
    },
    onError () {
      // console.log('连接失败' + this.ws.readyState)
      setTimeout(() => {
        this.init()
      }, 1000)
    },
    changeCurrent (page, limit) {
      this.current = page
      this.limit = limit
      this.getMsg()
    },
    async getMsg () {
      const res = await getUserMsg({ page: this.current, limit: this.limit })
      if (res.code === 200) {
        this.list = res.data
        this.total = res.total
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
